<!DOCTYPE html>
<html>

<head>

    <meta charset="utf-8">
    <meta name="viewport"
          content="width=device-width,  user-scalable=no">

    <title></title>
    <link rel="stylesheet" href="../../plugins/layui/css/layui.css"/>
    <link rel="stylesheet" href="../../css/fa.css"/>
    <link rel="stylesheet" href="../../css/icon.css"/>
    <link rel="stylesheet" href="../../css/ares_animate.min.css"/>
    <link rel="stylesheet" href="../../css/ares_hover_variant.min.css"/>
    <link rel="stylesheet" href="../../css/ares_reboot.css"/>
    <link rel="stylesheet" href="../../css/app.min.css"/>
    <link rel="stylesheet" href="../../css/iframe.css"/>
    <style>
        #msg-container .msg-block {
            position: relative;
            height: 100%;
            padding:10px 10px 30px;
            box-shadow: 0 2px 6px rgba(0, 0, 0, .1), 0 0 6px rgba(0, 0, 0, .1);
        }
        #msg-container .msg-block .msg-btns {
            position: absolute;
            bottom: 0;
            left: 0;
            width: 100%;
            padding:0 10px 5px;
        }
        .layui-laypage {
            margin: 0;
        }
    </style>
</head>

<body>
<form class="layui-form" lay-filter="search-form">
    <div class="layui-form-item ares-mb-0">
        <label class="layui-form-label">消息类型</label>
        <div class="layui-inline">
            <input type="radio" name="isRead" value="0" lay-filter="isRead" title="全部">
            <input type="radio" name="isRead" value="1" lay-filter="isRead" title="未读" checked>
            <input type="radio" name="isRead" value="2" lay-filter="isRead" title="已读">
        </div>
        <div class="layui-inline ares-px-lg">
            <div id="pagination" class="ares-text-center ares-d-inline-block ares-mr-lg"></div>
            <span>查询到消息共 <b id="msg-count" class="ares-text-red"></b> 条</span>
        </div>
    </div>
</form>
<div class="ares-px">
    <div id="msg-container" class="ares-row ares-align-items-stretch"></div>
</div>

</body>
<script type="text/javascript" src="../../plugins/layui/layui.js"></script>
<script type="text/javascript" src="../../aresExtends/config/layuiConfig.js"></script>
<script>
    /**
     * 业务类型
     *
     * 1：发布转诊（接收者）
     * 2：发布转诊成功（发起者收到系统通知）
     * 3：转诊被接收
     * 4：转诊消息过期
     *
     * 5：发布了新的训练/评估-->治疗师（新任务）
     * 6：发布了新的训练 -->治疗师（新患者）
     * 7：发布了新的训练 -->治疗师长（新患者）
     * //8：发布了新的训练成功/评估 -->医生收到系统通知
     *
     * 9：治疗师长安排训练/评估排课给治疗师 -->治疗师（新任务）
     * //10：治疗师长安排训/评估练排课给治疗师成功 -->治疗师长收到系统通知
     *
     * 11：治疗师长取消治疗师的训练/评估排课 -->治疗师（任务被取消）
     * //12：治疗师长取消治疗师的训练/评估练排课成功 -->治疗师长收到系统通知
     *
     * 13：治疗师长将A训练/评估排课调整给B -->A治疗师（任务被取消）
     * 14：治疗师长将A训练/评估排课调整给B -->B治疗师（新增任务）
     * //15：治疗师长将A训练/评估排课调整给B成功 -->治疗师长收到系统通知
     *
     * 16：治疗师长将训练/评估患者P负责人A更换为B -->A治疗师（患者被重新安排）
     * 17：治疗师长将训练/评估患者P负责人A更换为B -->B治疗师（新增患者）
     * //18：治疗师长将训练/评估患者P负责人A更换为B成功 -->治疗师长收到系统通知
     *
     * 19：治疗师完成评估（不包含重新评估） -->医生收到评估结果
     * //20：治疗师完成评估（不包含重新评估） -->治疗师收到系统通知
     */

        //桌面通知
    var notice_permission = null;
    if (window.Notification) {
        Notification.requestPermission().then(function (permission) {
            if (permission === 'granted') {
                notice_permission = true;
                console.log('用户允许通知');
            } else if (permission === 'denied') {
                console.log('用户拒绝通知');
            }
        });
    }

    layui.use(['form', 'laypage', 'conf', 'utils', 'mandyServices', 'store'], function (form, laypage, config, utils, mandyServices, store) {
        var pageSize = 12,
            markReadedStr = '<span class="mark-readed ares-float-left">' +
            '<i class="fa-circle ares-text-red ares-text-xs"></i>' +
            '<button class="layui-btn layui-btn-xs layui-btn-normal">标记已读</button></span>';

        init();
        msgInnerLinkBindMarkReaded();

        //接收系统推送的消息,更新消息列表或我的任务
        utils.ARES.webSocket && (utils.ARES.webSocket.onmessage = function (event) {
            console.log('@@@@@@@@@@@@@@@@websocket Message@@@@@@@@@@@@@@@@')
            console.log(event.data)
            if (event.data == '2') {
                sendNotice("消息提醒", {
                    body: '你有新的消息，请及时查看!',
                    tag: 'notice',
                    icon: './images/notice.gif',
                })
                intervalLoadNewData();
                $("#not-read-alarm").removeClass("hide");
            } else if (event.data == '1') {
                sendNotice("消息提醒", {
                    body: '你有新的任务，请及时完成!',
                    tag: 'notice',
                    icon: './images/notice.gif',
                })
            }
        })

        /**
         * @author: ares
         * @date: 2021/3/9 10:57
         * @description: 切换消息类型
         */
        form.on('radio(isRead)', function (data) {
            getPageList(1, config.pagination.limit);
        });

        /**
         * @author: ares
         * @date: 2021/3/9 9:44
         * @description: 分页查询
         * @param{number} currentPage
         * @param{number} pageSize
         */
        function getPageList(currentPage, pageSize) {
            var isRead = form.val('search-form').isRead;
            mandyServices.mandy_get_my_message_by_page(null, isRead, pageSize, currentPage).then(function (res) {
                var data = res.data;
                msgHandler.init(data.list);
                $('#msg-count').text(data.count);
                utils.laypageRender(laypage, $.extend(config.pagination, {
                    limit: pageSize,
                    count: data.count,
                    curr: data.current_page,
                    prev: '上一组',
                    next: '下一组',
                    layout: ['prev', 'next'],
                }), function (obj) {
                    getPageList(obj.curr, obj.limit);
                });
            });
        }

        /**
         * @author: ares
         * @date: 2021/3/20 15:41
         * @description: 发送桌面通知
         */
        function sendNotice(title, option) {
            return new Notification(title, option);
        }

        /**
         * @author: ares
         * @date: 2021/3/20 15:17
         * @description: 获取查看病例的url
         * @param{object} data  当前消息体
         */
        function getCheckEmrLink(data) {
            return '#/emr/info/' + JSON.parse(data.remark).out_emr.id + '?disEdit=1&mesEmr=1&transferId=' + data.buss_id;
        }

        /**
         * @author: ares
         * @date: 2021/3/20 15:47
         * @description: 消息中的a标签绑定标记已读操作
         */
        function msgInnerLinkBindMarkReaded() {
            $('#msg-container').on('click', 'a', function () {
                var msg = $(this).data('msg');
                msg.status == 0 && mandyServices.mandy_put_message_is_read(msg.id);
            })
        }

        /**
         * @author: ares
         * @date: 2021/3/20 14:39
         * @description: 标记消息为已读
         */
        function markReaded(data, callback) {
            mandyServices.mandy_put_message_is_read(data.id).then(function (res) {
                getPageList(1, config.pagination.limit);
                if (typeof callback == 'function') callback();
            });
        }

        /**
         * @author: ares
         * @date: 2021/3/20 14:36
         * @description: 接诊患者
         * @param{object} data  当前消息体
         * @param{function} callback
         */
        function clinicalReception(data, callback) {
            utils.confirm('是否确认接诊患者?', {icon: 3, title: '接诊'}, function (index) {
                mandyServices.mandy_put_referral_emr(data.buss_id, data.id).then(function (res) {
                    getPageList(1, config.pagination.limit);
                    utils.msgSuccess(res.message);
                    utils.layer.close(index);
                    if (typeof callback == 'function') callback();
                });
            })
        }

        /**
         * @author: ares
         * @date: 2021/3/20 10:48
         * @description: 系统消息
         * @param{string} container 消息容器id
         */
        function Msg(container) {
            this.msgList = [];
            this.$container = $('#' + container);
        }

        /**
         * @author: ares
         * @date: 2021/3/20 14:46
         * @description: 消息
         */
        Msg.prototype = {
            constructor: Msg,
            /**
             * @author: ares
             * @date: 2021/3/20 10:55
             * @description: 消息初始化
             * @param{array} msgList
             */
            init: function (msgList) {
                if (!Array.isArray(msgList)) return;
                for (var i = 0; i < msgList.length; i++) {
                    this.fontBold(msgList[i]);
                }
                this.msgList = msgList;
                this.renderMsg();
            },
            /**
             * @author: ares
             * @date: 2021/3/20 10:43
             * @description: 给需要加粗的文案添加b标签
             * @param {object}data  消息体
             */
            fontBold: function (data) {
                var boldMark = JSON.parse(data.bold),
                    content = data.content;
                for (var key in boldMark) {
                    var value = boldMark[key];
                    if (content.indexOf(value) > -1) {
                        content = content.replace(value, "<b> " + value + " </b>")
                    }
                }
                data._content = content;
                return content;

            },
            /**
             * @author: ares
             * @date: 2021/3/20 10:56
             * @description: 渲染消息
             */
            renderMsg: function () {
                var self = this,
                    $fragment = $(document.createDocumentFragment());
                $.each(this.msgList, function (idx, message) {
                    var $msgBlock = $('<div class="ares-p-sm ares-col-sm-6 ares-col-md-4">' +
                        '<div class="msg-block ares-rounded-xs">' +
                        '<div class="msg-create-time">' + message.create_time + '</div>' +
                        '<div class="msg-txt">' + message._content + '</div>' +
                        '</div>' +
                        '</div>'),
                        $btns = $('<div class="msg-btns ares-text-right ares-clearfix"></div>');
                    if (msgTypeHandler[message.buss_type]) {
                        $btns.append(msgTypeHandler[message.buss_type].renderBtns(message));
                    } else {
                        $btns.append(self.renderBtns(message));
                    }
                    $msgBlock.find('.msg-block').append($btns);
                    $fragment.append($msgBlock);
                })
                this.$container.empty().append($fragment);
            },
            /**
             * @author: ares
             * @date: 2021/3/20 12:07
             * @description: 渲染操作按钮
             * @param{object} 当前消息体
             */
            renderBtns: function (data) {
                var $fragment = $(document.createDocumentFragment()),
                    $markReaded = $(markReadedStr);
                if (data.is_read == 0) $fragment.prepend($markReaded);
                this.bindEvent($fragment, data);
                return $fragment;
            },
            /**
             * @author: ares
             * @date: 2021/3/20 13:10
             * @description: 绑定事件
             * @param{jquery dom} $btns
             * @param{object} 当前消息体
             */
            bindEvent: function ($btns, data) {
                var $markReaded = $btns.find('.mark-readed');
                $markReaded.length && $markReaded.on('click', function (event) {
                    markReaded(data)
                })
            },
            /**
             * @author: ares
             * @date: 2021/3/20 14:43
             * @description: 消息内容发生改变
             */
            changed: typeof changedCallback == 'function' ? changedCallback : function () {
                console.log('消息列表需要更新')
            }
        }

        /**
         * @author: ares
         * @date: 2021/3/20 11:27
         * @description: 消息类型
         */
        function MsgType() {

        }

        /**
         * @author: ares
         * @date: 2021/3/20 14:47
         * @description: 消息类型
         */
        MsgType.prototype = {
            constructor: MsgType,
            1: new Type1(),
            3: new Type3(),
            4: new Type4(),
            19: new Type19(),
            30: new Type30(),
        }

        /**
         * @author: ares
         * @date: 2021/3/20 14:45
         * @description: 消息类型1 (接诊)
         * @param{function} changedCallback
         */
        function Type1(changedCallback) {
            //当前登录用户id
            this.currentProfileId = store.session.set('profileId');
            /**
             * @author: ares
             * @date: 2021/3/20 12:07
             * @description: 渲染操作按钮
             * @param{object} 当前消息体
             */
            this.renderBtns = function (data) {
                var $fragment = $(document.createDocumentFragment()),
                    $checkEmrLink = $('<a data-msgid="' + data.id + '" class="layui-btn layui-btn-xs" href="' + getCheckEmrLink(data) + '")>查看病历</a>'),
                    $disabledCheckEmrBtn = $('<button class="layui-btn layui-btn-xs layui-btn-disabled">查看病历</button>'),
                    $clinicalReception = $('<button class="clinical-reception layui-btn layui-btn-xs">接诊</button>'),
                    $DisabledClinicalReception = $('<button class="layui-btn layui-btn-xs layui-btn-disabled">接诊</button>'),
                    $yetClinicalReception = $('<button class="layui-btn layui-btn-xs layui-btn-disabled">已接诊</button>')
                $markReaded = $(markReadedStr);

                if (data.receive_status == 0) {
                    $fragment.append($checkEmrLink);
                    if (data.status >= 2 && data.status <= 4) {
                        $fragment.append($DisabledClinicalReception);
                    } else {
                        $fragment.append($clinicalReception);
                    }
                } else if (data.receive_status == 1) {
                    if (data.status == 1) {
                        $fragment.append($checkEmrLink);
                    } else if (data.status == 2) {
                        if (data.performer == null || data.performer == 'null' || data.performer.id == this.currentProfileId) {
                            $fragment.append($checkEmrLink);
                        } else if (data.performer.id != this.currentProfileId) {
                            $fragment.append($disabledCheckEmrBtn);
                        }
                    } else if (data.status == 3 || data.status == 4) {
                        $fragment.append($disabledCheckEmrBtn);
                    }
                    $fragment.append($yetClinicalReception);
                }
                if (data.is_read == 0) $fragment.prepend($markReaded);
                this.bindEvent($fragment, data);
                return $fragment;
            }
            /**
             * @author: ares
             * @date: 2021/3/20 13:10
             * @description: 绑定事件
             * @param{jquery dom} $btns
             * @param{object} 当前消息体
             */
            this.bindEvent = function ($btns, data) {
                var $markReaded = $btns.find('.mark-readed'),
                    $clinicalReception = $btns.find('.clinical-reception');
                $markReaded.length && $markReaded.on('click', function (event) {
                    markReaded(data)
                })
                $clinicalReception.length && $clinicalReception.on('click', function (event) {
                    clinicalReception(data)
                })
            }
            /**
             * @author: ares
             * @date: 2021/3/20 14:43
             * @description: 消息内容发生改变
             */
            this.changed = typeof changedCallback == 'function' ? changedCallback : function () {
                console.log('消息列表需要更新')
            }
        }

        /**
         * @author: ares
         * @date: 2021/3/20 14:45
         * @description: 消息类型3 (转诊)
         * @param{function} changedCallback
         */
        function Type3(changedCallback) {
            /**
             * @author: ares
             * @date: 2021/3/20 12:07
             * @description: 渲染操作按钮
             * @param{object} 当前消息体
             */
            this.renderBtns = function (data) {
                var $fragment = $(document.createDocumentFragment()),
                    $checkEmrLink = $('<a data-msgid="' + data.id + '" class="layui-btn layui-btn-xs" href="' + getCheckEmrLink(data) + '")>查看病历</a>'),
                    $toReferralLink = $('<a data-msgid="' + data.id + '" class="layui-btn layui-btn-xs" href="#/referral/list")>前往转诊</a>'),
                    $markReaded = $(markReadedStr);
                if (data.status != 3 && data.status != 4) $fragment.append($checkEmrLink, $toReferralLink);
                if (data.is_read == 0) $fragment.prepend($markReaded);
                this.bindEvent($fragment, data);
                return $fragment;
            }
            /**
             * @author: ares
             * @date: 2021/3/20 13:10
             * @description: 绑定事件
             * @param{jquery dom} $btns
             * @param{object} 当前消息体
             */
            this.bindEvent = function ($btns, data) {
                var $markReaded = $btns.find('.mark-readed');
                $markReaded.length && $markReaded.on('click', function (event) {
                    markReaded(data)
                })
            }
            /**
             * @author: ares
             * @date: 2021/3/20 14:43
             * @description: 消息内容发生改变
             */
            this.changed = typeof changedCallback == 'function' ? changedCallback : function () {
                console.log('消息列表需要更新')
            }
        }

        /**
         * @author: ares
         * @date: 2021/3/20 14:46
         * @description: 消息类型4
         * @param{function} changedCallback
         */
        function Type4(changedCallback) {
            /**
             * @author: ares
             * @date: 2021/3/20 12:07
             * @description: 渲染操作按钮
             * @param{object} 当前消息体
             */
            this.renderBtns = function (data) {
                var $fragment = $(document.createDocumentFragment()),
                    $checkEmrLink = $('<a data-msgid="' + data.id + '" class="layui-btn layui-btn-xs" href="' + getCheckEmrLink(data) + '")>查看病历</a>'),
                    $markReaded = $(markReadedStr);
                if (data.status != 3 && data.status != 4) $fragment.append($checkEmrLink);
                if (data.is_read == 0) $fragment.prepend($markReaded);
                this.bindEvent($fragment, data);
                return $fragment;
            }
            /**
             * @author: ares
             * @date: 2021/3/20 13:10
             * @description: 绑定事件
             * @param{jquery dom} $btns
             * @param{object} 当前消息体
             */
            this.bindEvent = function ($btns, data) {
                var $markReaded = $btns.find('.mark-readed');
                $markReaded.length && $markReaded.on('click', function (event) {
                    markReaded(data)
                })
            }
            /**
             * @author: ares
             * @date: 2021/3/20 14:43
             * @description: 消息内容发生改变
             */
            this.changed = typeof changedCallback == 'function' ? changedCallback : function () {
                console.log('消息列表需要更新')
            }
        }

        /**
         * @author: ares
         * @date: 2021/3/20 14:46
         * @description: 消息类型19 (评估)
         * @param{function} changedCallback
         */
        function Type19(changedCallback) {
            /**
             * @author: ares
             * @date: 2021/3/20 12:07
             * @description: 渲染操作按钮
             * @param{object} 当前消息体
             */
            this.renderBtns = function (data) {
                var $fragment = $(document.createDocumentFragment()),
                    $checkPrcpLink = $('<a class="layui-btn layui-btn-xs" href="#/evaluation/gauge?prcpItemId='+data.buss_id+'")>查看评估</a>'),
                    $markReaded = $(markReadedStr);
                $checkPrcpLink.data('msg',data);
                if (data.status != 3 && data.status != 4) $fragment.append($checkPrcpLink);
                if (data.is_read == 0) $fragment.prepend($markReaded);
                this.bindEvent($fragment, data);
                return $fragment;
            }
            /**
             * @author: ares
             * @date: 2021/3/20 13:10
             * @description: 绑定事件
             * @param{jquery dom} $btns
             * @param{object} 当前消息体
             */
            this.bindEvent = function ($btns, data) {
                var $markReaded = $btns.find('.mark-readed');
                $markReaded.length && $markReaded.on('click', function (event) {
                    markReaded(data)
                })
            }
            /**
             * @author: ares
             * @date: 2021/3/20 14:43
             * @description: 消息内容发生改变
             */
            this.changed = typeof changedCallback == 'function' ? changedCallback : function () {
                console.log('消息列表需要更新')
            }
        }

        /**
         * @author: ares
         * @date: 2021/3/20 14:46
         * @description: 消息类型30
         * @param{function} changedCallback
         */
        function Type30(changedCallback) {
            /**
             * @author: ares
             * @date: 2021/3/20 12:07
             * @description: 渲染操作按钮
             * @param{object} 当前消息体
             */
            this.renderBtns = function (data) {
                var $fragment = $(document.createDocumentFragment()),
                    $checkEmrLink = $('<a data-msgid="' + data.id + '" class="layui-btn layui-btn-xs" href="' + getCheckEmrLink(data) + '")>查看病历</a>'),
                    $markReaded = $(markReadedStr);
                if (data.status != 3 && data.status != 4) $fragment.append($checkEmrLink);
                if (data.is_read == 0) $fragment.prepend($markReaded);
                this.bindEvent($fragment, data);
                return $fragment;
            }
            /**
             * @author: ares
             * @date: 2021/3/20 13:10
             * @description: 绑定事件
             * @param{jquery dom} $btns
             * @param{object} 当前消息体
             */
            this.bindEvent = function ($btns, data) {
                var $markReaded = $btns.find('.mark-readed');
                $markReaded.length && $markReaded.on('click', function (event) {
                    markReaded(data)
                })
            }
            /**
             * @author: ares
             * @date: 2021/3/20 14:43
             * @description: 消息内容发生改变
             */
            this.changed = typeof changedCallback == 'function' ? changedCallback : function () {
                console.log('消息列表需要更新')
            }
        }

        var msgHandler = new Msg('msg-container'),
            msgTypeHandler = new MsgType();

        /**
         * @author: ares
         * @date: 2021/3/20 15:46
         * @description: 初始化
         */
        function init() {
            getPageList(1, pageSize);
        }
    })

</script>

</html>
